//获取数据并渲染
function showCategory() {
  $.ajax({
    url: "/my/category/list",
    success: (res) => {
      $("tbody").empty();
      $.each(res.data, (index, item) => {
        $(`
          <tr>
            <td>${item.name}</td>
            <td>${item.alias}</td>
            <td>
              <button type="button"
              data-name=${item.name}
              data-alias=${item.alias}
              data-id=${item.id}
              class="layui-btn layui-btn-xs">
                编辑
              </button>
              <button
                type="button"
                data-id=${item.id}
                class="layui-btn  layui-btn-xs layui-btn-danger del"
              >
                删除
              </button>
            </td>
          </tr>`).appendTo($("tbody"));
      });
    },
  });
}
showCategory();
//点击添加类别弹窗
let getAdd;
$('button:contains("添加类别")').on("click", function () {
  //弹框
  getAdd = layer.open({
    title: "添加分类",
    type: 1,
    area: ["500px", "250px"],
    content: `${$(".add").html()}`,
  });
});
//表单提交,事件委托
$("body").on("submit", ".addform", function (e) {
  e.preventDefault();
  let data = $(this).serialize();
  $.ajax({
    type: "post",
    url: "/my/category/add",
    data,
    success: (res) => {
      layer.msg(res.message);
      if (res.status === 0) {
        showCategory();
        //关闭弹框
        layer.close(getAdd);
      }
    },
  });
});
//重置
$("body").on("click", ".reset", function () {
  $(this).parents("form")[0].reset();
});
//点击编辑,数据回填
let editadd;
$("tbody").on("click", 'button:contains("编辑")', function () {
  //获取值并数据回填
  let data = $(this).data();
  //弹窗
  editadd = layer.open({
    type: 1,
    title: "编辑分类",
    content: $(".edit").html(),
    area: ["500px", "250px"],
    success: () => {
      let form = layui.form;
      form.val("editform", data);
    },
  });
});
//表单submit事件
$("body").on("submit", ".editform", function (e) {
  e.preventDefault();
  let val = $(this).serialize();
  $.ajax({
    type: "post",
    url: "/my/category/update",
    data: val,
    success: (res) => {
      layer.msg(res.message);
      if (res.status === 0) {
        showCategory();
        layer.close(editadd);
      }
    },
  });
});
//删除功能
$("tbody").on("click", ".del", function () {
  let id = $(this).data("id");
  layer.confirm("您确定删除吗?", function (index) {
    $.ajax({
      url: `/my/category/delete?id=${id}`,
      success: (res) => {
        if (res.status === 0) {
          layer.msg(
            res.message,
            {
              time: 1000, //2秒关闭（如果不配置，默认是3秒）
            },
            function () {
              //再次渲染
              showCategory();
            }
          );
        } else {
          layer.msg(res.message);
        }
      },
    });
    layer.close(index);
  });
});
